﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace SmartDeviceProject9
{
    public partial class NSrcDBForm : Form
    {
        public NSrcDBForm()
        {
            InitializeComponent();
        }

        public Form ParentForm { get; set; }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool closeNoEnsure = true;


        private void NSrcDBForm_Closing(object sender, CancelEventArgs e)
        {

            if (closeNoEnsure)
            {
                if (MessageBox.Show("关闭后，当前数据将丢失，是否继续？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    closeNoEnsure = false;
                    this.Close();

                }
            }
            else
            {

                e.Cancel = false;
            }
            ParentForm.Show();
        }


        private DataTable bindDataSource;
        private DataTable ResultsTable;      //保存所有查询出的物料信息
        private DataSet dataS = new DataSet();
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NSrcDBForm_Load(object sender, EventArgs e)
        {

            Type type = typeof(string);
            bindDataSource = new DataTable();
            bindDataSource.Columns.Add(new DataColumn("条码", type));
            bindDataSource.Columns.Add(new DataColumn("原纸名称", type));
            bindDataSource.Columns.Add(new DataColumn("幅宽", type));
            bindDataSource.Columns.Add(new DataColumn("现存量", type));
            this.dataGrid1.DataSource = bindDataSource;

            ResultsTable = new DataTable();
            //物料编码
            ResultsTable.Columns.Add(new DataColumn("FMaterialId", type));
            //物料名
            ResultsTable.Columns.Add(new DataColumn("FMaterialName", type));
            //条码
            ResultsTable.Columns.Add(new DataColumn("FBarCode", type));
            //基本数量
            ResultsTable.Columns.Add(new DataColumn("FBaseQty", type));
            //基础单位
            ResultsTable.Columns.Add(new DataColumn("FBaseUnitId", type));
            //幅宽
            ResultsTable.Columns.Add(new DataColumn("FAuxPropId", type));

            //bindDataSource.Rows.InsertAt( ,0);

            dataS.Tables.Add(ResultsTable);
            #region  设置组织仓库
            DataTable table = new DataTable();
            DataTable table2 = new DataTable();
            table.Columns.Add("OrgId", type);
            table.Columns.Add("Name", type);


            table2.Columns.Add("OrgId", type);
            table2.Columns.Add("Name", type);

            int i = -1;
            int selectIndex = -1;
            foreach (var org in Context.Orgs)
            {
                i++;
                DataRow dr = table.NewRow();
                dr["OrgId"] = org.Value.OrgId;
                dr["Name"] = org.Value.Name;
                DataRow dr2 = table2.NewRow();
                dr2["OrgId"] = org.Value.OrgId;
                dr2["Name"] = org.Value.Name;
                if (org.Value.OrgId == Context.UserCurrentOrgId)
                {
                    selectIndex = i;
                }
                table.Rows.Add(dr);
                table2.Rows.Add(dr2);
            }
            //调出组织
            comboBox2.DataSource = table;
            comboBox2.DisplayMember = "Name";
            comboBox2.ValueMember = "OrgId";




            //调入组织
            comboBox1.DataSource = table2;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "OrgId";

            if (selectIndex >= 0)
            {
                comboBox1.SelectedIndex = selectIndex;
                comboBox1_SelectedIndexChanged(null, null);
                comboBox2.SelectedIndex = selectIndex;
                comboBox2_SelectedIndexChanged(null, null);
            }
            #endregion



        }

        /// <summary>
        /// 条码回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {

            #region 条码回车事件

            if (e.KeyCode == Keys.Enter)
            {


                string s = this.tbxCode.Text.Trim();

                this.tbxCode.Text = string.Empty;

                this.tbxCode.Focus();

                if (string.IsNullOrEmpty(s) || s == "")
                    return;

                foreach (DataRow row in bindDataSource.Rows)
                {
                    if (Convert.ToString(row["条码"]) == s)
                    {
                        MessageBox.Show("条码重复:" + s);
                        return;
                    }
                }
                string orgId = this.comboBox2.SelectedValue as string;
                string stockId = this.comboBox3.SelectedValue as string;

                //物料编码           物料名        条码      基础数量     基础单位       幅宽
                //FMaterialId,  FMaterialFName, FBarCode,  FBaseQty,  FBaseUnitId,    FAuxPropId
                DataSet dataSet = Context.Service.GetCodeDetail(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, s,orgId,stockId,true);
                //if (dataSet == null) 
                if (dataSet != null)
                {
                    DataRow nrow = bindDataSource.NewRow();
                    DataTable table = dataSet.Tables[0];
                    nrow["条码"] = s;
                    nrow["原纸名称"] = table.Rows[0]["FMaterialFName"];
                    nrow["幅宽"] = table.Rows[0]["FAuxPropId"];
                    nrow["现存量"] =Convert.ToDecimal( table.Rows[0]["FBaseQty"]).ToString("0.##");
                    bindDataSource.Rows.Add(nrow);

                    //数据取出保存
                    DataRow drRow = ResultsTable.NewRow();
                    drRow["FMaterialId"] = table.Rows[0]["FMaterialId"];
                    drRow["FMaterialName"] = table.Rows[0]["FMaterialFName"];
                    drRow["FBarCode"] = table.Rows[0]["FBarCode"];
                    drRow["FBaseQty"] = table.Rows[0]["FBaseQty"];
                    drRow["FBaseUnitId"] = table.Rows[0]["FBaseUnitId"];
                    drRow["FAuxPropId"] = table.Rows[0]["FAuxPropId"];
                    ResultsTable.Rows.Add(drRow);
                }
                else
                {
                    MessageBox.Show("未查到相关条码信息,或者该条码数量不足");
                }


            }

            #endregion

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable table = this.dataGrid1.DataSource as DataTable;
            if (table == null || table.Rows.Count == 0) return;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItem1_Click(object sender, EventArgs e)
        {

            #region 保存按钮

            //调用服务， 把数据，传递给服务接口。 
            // 条码等....
            //调拨类型
            if (ResultsTable.Rows.Count <= 0)
            {
                MessageBox.Show("至少录入一条 条码");
                return;
            }
            bool transferBizType = this.radioButton2.Checked;
            string bizType = "InnerOrgTransfer";      //组织内调拨
            if (transferBizType == false)
            {
                bizType = "OverOrgTransfer";          //组织间调拨
                transferBizType = this.radioButton1.Checked;
                if (transferBizType == false)
                {
                    MessageBox.Show("请选择调拨类型");
                    return;
                }

            }
            List<string> listStr = new List<string>();
            string outOrg = this.comboBox2.SelectedValue as string;      //调出库存组织      获取的是Id
            string outStock = this.comboBox3.SelectedValue as string;    //调出仓库
            string inOrg = this.comboBox1.SelectedValue as string;       //调入库存组织
            string inStock = this.comboBox4.SelectedValue as string;     //调入仓库
            if (bizType == "InnerOrgTransfer" && outOrg != inOrg)
            {
                MessageBox.Show("组织内调拨 调出组织和调入组织必须 一至");
                return;
            }
            if (bizType == "OverOrgTransfer" && outOrg == inOrg)
            {
                MessageBox.Show("组织间调拨 调出组织和调入组织必须 不一至");
                return;
            }
            if (outOrg == inOrg && outStock == inStock)
            {
                MessageBox.Show("同组织同仓库不能调拨，请修改");
                return;
            }
            listStr = ZZCK(outOrg, outStock);
            if (listStr == null)
            {
                MessageBox.Show("请选择正确的调 出 库存或调 出 仓库");
                return;
            }
            outOrg = listStr[0];
            outStock = listStr[1];
            listStr = ZZCK(inOrg, inStock);
            if (listStr == null)
            {
                MessageBox.Show("请选择正确的调 入 库存或调 入 仓库");
                return;
            }
            inOrg = listStr[0];
            inStock = listStr[1];
            //调拨类型  调出组织   调出仓库  调入组织 调入仓库   条码信息
            string messStr = Context.Service.SaveSTKTransferDirect(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, bizType, outOrg, outStock, inOrg, inStock, dataS);
            dataS.Tables[0].Rows.Clear();
            (dataGrid1.DataSource as DataTable).Rows.Clear();
            MessageBox.Show(messStr);
            #endregion


        }
        /// <summary>
        /// 查询库存组织和仓库 （ 编号 ）
        /// </summary>
        /// <param name="orgId">组织Id</param>
        /// <param name="stkId">仓库id</param>
        /// <returns>0 为 组织   1 为仓库</returns>
        private List<string> ZZCK(string orgId, string stkId)
        {
            List<string> listStr = new List<string>();
            foreach (var org in Context.Orgs)
            {
                if (org.Key == orgId)
                {
                    listStr.Add(org.Value.Number);
                    foreach (Stk s in org.Value._stks)
                    {
                        if (s.StkId == stkId)
                            listStr.Add(s.Number);
                    }
                }
            }
            if (listStr.Count == 2)
                return listStr;
            return null;
        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            bool transferBizType = this.radioButton2.Checked;
            if (transferBizType)
            {
                comboBox1.SelectedValue = comboBox2.SelectedValue;
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            bool transferBizType = this.radioButton1.Checked;
            if (transferBizType && comboBox2.SelectedValue == comboBox1.SelectedValue)
            {
                int co = comboBox1.Items.Count;
                int i = comboBox1.SelectedIndex;
                if (co == 1)
                {
                    this.radioButton1.Checked = false;
                    this.radioButton2.Checked = true;
                }
                else if (i == co - 1)
                {
                    comboBox1.SelectedIndex = i - 1;
                }
                else
                {
                    comboBox1.SelectedIndex = i + 1;
                }
            }
        }

        private void tbxCode_TextChanged(object sender, EventArgs e)
        {

        }

        private void menuItem2_Popup(object sender, EventArgs e)
        {

        }

        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        ///调出仓库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            //清空缓存
            ResultsTable.Rows.Clear();
            bindDataSource.Rows.Clear();
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 调入仓库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 调出组织
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Type type = typeof(string);

            //清空缓存
            ResultsTable.Rows.Clear();
            bindDataSource.Rows.Clear();

            //调出仓库组织
            string org = comboBox2.SelectedValue as string;
            if (org != null && org != "")
            {
                DataTable table = new DataTable();
                table.Columns.Add("StkId", type);
                table.Columns.Add("name", type);

                List<Stk> listStk = Context.Orgs[org]._stks;
                foreach (Stk s in listStk)
                {
                    DataRow dr = table.NewRow();
                    dr["StkId"] = s.StkId;
                    dr["name"] = s.Name;
                    table.Rows.Add(dr);
                }
                comboBox3.DataSource = table;
                comboBox3.DisplayMember = "name";
                comboBox3.ValueMember = "StkId";
            }
            bool transferBizType = this.radioButton2.Checked;
            if (transferBizType == true)
            {
                comboBox1.SelectedValue = comboBox2.SelectedValue;
            }

        }
        /// <summary>
        /// 调入组织
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Type type = typeof(string);
            //调入仓库组织
            string org = comboBox1.SelectedValue as string;
            if (org != null && org != "")
            {
                DataTable table = new DataTable();
                table.Columns.Add("StkId", type);
                table.Columns.Add("name", type);

                List<Stk> listStk = Context.Orgs[org]._stks;
                foreach (Stk s in listStk)
                {
                    DataRow dr = table.NewRow();
                    dr["StkId"] = s.StkId;
                    dr["name"] = s.Name;
                    table.Rows.Add(dr);
                }
                comboBox4.DataSource = table;
                comboBox4.DisplayMember = "name";
                comboBox4.ValueMember = "StkId";
            }
            bool transferBizType = this.radioButton2.Checked;
            if (transferBizType == true)
            {
                comboBox2.SelectedValue = comboBox1.SelectedValue;
            }
        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 双击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGrid1_DoubleClick(object sender, EventArgs e)
        {
            int index = this.dataGrid1.CurrentRowIndex;
            if (index != -1)
            {
                bindDataSource.Rows.RemoveAt(index);
                ResultsTable.Rows.RemoveAt(index);
            
            }
            
        }
    }

}